#!/bin/bash

# Deployed images in media-node
IMAGES=(
  "kurento-media-server"
  "docker.elastic.co/beats/filebeat"
  "docker.elastic.co/beats/metricbeat"
  "openvidu/media-node-controller"
)

docker_command_by_container_image() {
  IMAGE_NAME=$1
  COMMAND=$2
  if  [[ -n "${IMAGE_NAME}" ]]; then
    CONTAINERS="$(docker ps -a | grep "${IMAGE_NAME}" | awk '{print $1}')"
    for CONTAINER_ID in $CONTAINERS; do
      if [[ -n "${CONTAINER_ID}" ]] && [[ -n "${COMMAND}" ]]; then
        bash -c "docker ${COMMAND} ${CONTAINER_ID}"
      fi
    done
  fi
}


stop_containers() {
  printf "Stopping containers..."
  for IMAGE in "${IMAGES[@]}"; do
    docker_command_by_container_image "${IMAGE}" "rm -f"
  done
}
kurento_logs() {
  if [[ "$1" == "-f" ]]; then
    tail -f /opt/openvidu/kurento-logs/*.log
  else
    cat /opt/openvidu/kurento-logs/*.log
  fi
}

upgrade_media_node() {
  UPGRADE_SCRIPT_URL="https://s3-eu-west-1.amazonaws.com/aws.openvidu.io/install_media_node_OVVERSION.sh"
  HTTP_STATUS=$(curl -s -o /dev/null -I -w "%{http_code}" ${UPGRADE_SCRIPT_URL//OVVERSION/$1})

  printf "  => Upgrading Media Node to '%s' version" "$1"

  if [ "$HTTP_STATUS" == "200" ]; then
    printf "\n    => Downloading and upgrading new version"
    printf "\n"

    curl --silent ${UPGRADE_SCRIPT_URL//OVVERSION/$1} | bash -s upgrade
  else
     printf "\n     =======¡ERROR!======="
     printf "\n     Media Node Version %s not exist" "$1"
     printf "\n"
     exit 0
  fi
}

collect_basic_information() {
  LINUX_VERSION=$(lsb_release -d)
  DOCKER_PS=$(docker ps)
  DOCKER_VERSION=$(docker version --format '{{.Server.Version}}')
  DOCKER_COMPOSE_VERSION=$(docker-compose version --short)
  MEDIA_NODE_FOLDER="${PWD}"
  OV_VERSION=$(grep 'Openvidu Version:' "${MEDIA_NODE_FOLDER}/docker-compose.yml" | awk '{ print $4 }')
  OV_TYPE_INSTALLATION=$(grep 'Installation Mode:' "${MEDIA_NODE_FOLDER}/docker-compose.yml" | awk '{ print $4,$5 }')
  TREE_OV_DIRECTORY=$(find "." | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/")
}

version_ov() {
  collect_basic_information

  printf '\nMedia Node Information:'
  printf '\n'
  printf '\n  Installation Type: %s' "${OV_TYPE_INSTALLATION}"
  printf '\n  Openvidu Version: %s' "${OV_VERSION}"
  printf '\n'
  printf '\nSystem Information:'
  printf '\n'
  printf '\n  Linux Version:'
  printf '\n    - %s' "${LINUX_VERSION}"
  printf '\n  Docker Version: %s' "${DOCKER_VERSION}"
  printf '\n  Docker Compose Version: %s' "${DOCKER_COMPOSE_VERSION}"
  printf '\n'
  printf '\nInstallation Information:'
  printf '\n'
  printf '\n  Installation Folder: %s' "${MEDIA_NODE_FOLDER}"
  printf '\n  Installation Folder Tree:'
  printf '\n%s' "$(echo "${TREE_OV_DIRECTORY}" | sed -e 's/.//' -e ':a' -e 'N;$!ba' -e 's/\n/\n\t/g')"
  printf '\n'
  printf '\nDocker Running Services:'
  printf '\n'
  printf '\n  %s' "$(echo "${DOCKER_PS}" | sed -e ':a' -e 'N;$!ba' -e 's/\n/\n\t/g')"
  printf '\n'
}

generate_report() {
  collect_basic_information

  REPORT_CREATION_DATE=$(date +"%d-%m-%Y")
  REPORT_CREATION_TIME=$(date +"%H:%M:%S")
  REPORT_NAME="media-node-report-${REPORT_CREATION_DATE}-$(date +"%H-%M").txt"
  REPORT_OUTPUT="${MEDIA_NODE_FOLDER}/${REPORT_NAME}"
  CONTAINERS=$(docker ps | awk '{if(NR>1) print $NF}')

  {
    printf "\n  ======================================="
    printf "\n  =         REPORT INFORMATION          ="
    printf "\n  ======================================="
    printf '\n'
    printf '\n  Creation Date: %s' "${REPORT_CREATION_DATE}"
    printf '\n  Creation Time: %s' "${REPORT_CREATION_TIME}"
    printf '\n'
    printf "\n  ======================================="
    printf "\n  =       MEDIA NODE INFORMATION        ="
    printf "\n  ======================================="
    printf '\n'
    printf '\n  Installation Type: %s' "${OV_TYPE_INSTALLATION}"
    printf '\n  Openvidu Version: %s' "${OV_VERSION}"
    printf '\n'
    printf "\n  ======================================="
    printf "\n  =         SYSTEM INFORMATION          ="
    printf "\n  ======================================="
    printf '\n'
    printf '\n  Linux Version:'
    printf '\n    - %s' "${LINUX_VERSION}"
    printf '\n  Docker Version: %s' "${DOCKER_VERSION}"
    printf '\n  Docker Compose Version: %s' "${DOCKER_COMPOSE_VERSION}"
    printf '\n'
    printf "\n  ======================================="
    printf "\n  =     INSTALLATION INFORMATION        ="
    printf "\n  ======================================="
    printf '\n'
    printf '\n  Installation Folder: %s' "${MEDIA_NODE_FOLDER}"
    printf '\n  Installation Folder Tree:'
    printf '\n%s' "$(echo "${TREE_OV_DIRECTORY}" | sed -e 's/.//' -e ':a' -e 'N;$!ba' -e 's/\n/\n\t/g')"
    printf '\n'
    printf "\n  ======================================="
    printf "\n  =      DOCKER RUNNING SERVICES        ="
    printf "\n  ======================================="
    printf '\n'
    printf '\n  %s' "$(echo "${DOCKER_PS}" | sed -e ':a' -e 'N;$!ba' -e 's/\n/\n\t/g')"
    printf '\n'
    printf "\n  ======================================="
    printf "\n  =        CONFIGURATION FILES          ="
    printf "\n  ======================================="
    printf '\n'
    printf '\n  ================ .env ================='
    printf '\n'
    printf '\n'

    cat < "${MEDIA_NODE_FOLDER}/.env"

    printf '\n'
    printf '\n  ========= docker-compose.yml =========='
    printf '\n'
    printf '\n'

    cat "${MEDIA_NODE_FOLDER}/docker-compose.yml"

    printf '\n'
    printf '\n'
    printf "\n  ======================================="
    printf "\n  =                LOGS                 ="
    printf "\n  ======================================="

    for CONTAINER in $CONTAINERS
    do
      printf '\n'
      printf "\n  ---------------------------------------"
      printf "\n  %s" "$CONTAINER"
      printf "\n  ---------------------------------------"
      printf '\n'
      docker logs "$CONTAINER"
      printf "\n  ---------------------------------------"
      printf '\n'
      printf '\n'
    done

    printf '\n'
    printf "\n  ---------------------------------------"
    printf "\n  KMS"
    printf "\n  ---------------------------------------"
    printf '\n'
    kurento_logs
    printf "\n  ---------------------------------------"
    printf '\n'
    printf '\n'

    printf "\n  ======================================="
    printf "\n  =       CONTAINER ENVS VARIABLES      ="
    printf "\n  ======================================="

    for CONTAINER in $CONTAINERS
    do
      printf '\n'
      printf "\n  ======================================="
      printf "\n  %s" "$CONTAINER"
      printf "\n  ---------------------------------------"
      printf '\n'
      docker exec "$CONTAINER" env
      printf "\n  ---------------------------------------"
      printf '\n'
      printf '\n'
    done

  } >> "${REPORT_OUTPUT}" 2>&1

  printf "\n  Generation of the report completed with success"
  printf "\n  You can get your report at path '%s'" "${REPORT_OUTPUT}"
  printf "\n"
}

usage() {
    printf "Usage: \n\t media_node [command]"
    printf "\n\nAvailable Commands:"
    printf "\n\tstart\t\t\tStart media node service"
    printf "\n\tstop\t\t\tStop media node service"
    printf "\n\trestart\t\t\tRestart media node service"
    printf "\n\tlogs [-f]\t\tShow media-node-controller logs."
    printf "\n\tkms-logs [-f]\t\tShow kms logs"
    printf "\n\tupgrade\t\t\tUpgrade to the latest Media Node version"
    printf "\n\tupgrade [version]\tUpgrade to the specific Media Node version"
    printf "\n\tversion\t\t\tShow version of Media Node"
    printf "\n\treport\t\t\tGenerate a report with the current status of Media Node"
    printf "\n\thelp\t\t\tShow help for media node command"
    printf "\n"
}

case $1 in

  start)
    docker-compose up -d
    docker-compose logs -f media-node-controller
    ;;

  stop)
    docker-compose down
    stop_containers
    ;;

  restart)
    docker-compose down
    stop_containers
    docker-compose up -d
    docker-compose logs -f media-node-controller
    ;;

  logs)
    case $2 in
      "-f")
        docker-compose logs -f media-node-controller
        ;;
      *)
        docker-compose logs media-node-controller
        ;;
    esac
    ;;

  kms-logs)
    kurento_logs "$2"
    ;;

  upgrade)
    if [ -z "$2" ]; then
      UPGRADE_VERSION="latest"
    else
      UPGRADE_VERSION="$2"
    fi

    read -r -p "  You're about to update Media Node to '${UPGRADE_VERSION}' version. Are you sure? [y/N]: " response
    case "$response" in
    [yY][eE][sS]|[yY])
    	upgrade_media_node "${UPGRADE_VERSION}"
        ;;
    *)
        exit 0
        ;;
    esac
    ;;

  version)
    version_ov
    ;;

  report)
    read -r -p "  You are about to generate a report on the current status of Media Node, this may take some time. Do you want to continue? [y/N]: " response
    case "$response" in
      [yY][eE][sS]|[yY])
        generate_report
        ;;
      *)
        exit 0
        ;;
    esac
    ;;

  *)
    usage
    ;;
esac
